package cn._2dland.websocket;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import cn._2dland.websocket.handler.AbstractConnectionHandler;

/**
 * WebSocket服务器
 * 
 * @author deadblue
 */
public class WebSocketServer extends Thread {

	/** 监听端口 */
	private int port = 11111;

	private List<WebSocketConnection> onlineClients = null;
	
	public WebSocketServer(int port) {
		this.port = port;

		// 初始化在线客户端列表
		onlineClients = new ArrayList<WebSocketConnection>();
	}

	@Override
	public void run() {
		try {
			ServerSocket serverSock = new ServerSocket();
			serverSock.bind(new InetSocketAddress("0.0.0.0", port));
			System.out.println("WebSocket服务器启动，监听端口: " + port);

			while(true) {
				// 接受连接
				Socket clientSock = serverSock.accept();
				// 开启线程
				WebSocketConnection client = new WebSocketConnection(this, clientSock);
				client.addHandler(new AbstractConnectionHandler() {
					@Override
					public void onTextMessage(WebSocketConnection conn,
							String text) {
						System.out.println("文本到达: " + text);
					}
					
					@Override
					public void onClose(WebSocketConnection conn) {
						System.out.println("连接已断开...");
					}
				});
				client.start();
				onlineClients.add(client);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}